<template>
  <div class="home-container">
    <!-- Top section with categories and login -->
    <div class="top-section">
      <div class="main-content-wrapper">
        <!-- Left Categories -->
        <div class="left-category-nav">
          <ul>
            <li v-for="cat in categories" :key="cat.name">
              <el-icon><component :is="cat.icon" /></el-icon>
              <span>{{ cat.name }}</span>
              <span class="sub-text">{{ cat.sub }}</span>
            </li>
          </ul>
        </div>

        <!-- Middle content (Image placeholder) -->
        <div class="middle-content">
           <el-carousel :interval="5000" arrow="always" height="320px">
            <el-carousel-item v-for="item in carouselItems" :key="item.id">
              <img :src="item.image" class="carousel-image"/>
            </el-carousel-item>
          </el-carousel>
        </div>

        <!-- Right Login/User Info -->
        <div class="right-user-card">
          <div v-if="userStore.isLoggedIn && userStore.userInfo" class="user-info-card">
            <el-avatar :size="50" class="user-avatar">
              {{ userStore.userInfo.name?.charAt(0).toUpperCase() || 'U' }}
            </el-avatar>
            <h4>Hi, {{ userStore.userInfo.name }}</h4>
            <p>继续您的学习之旅吧！</p>
            <el-button type="primary" round @click="goTo('/profile')">我的课程</el-button>
          </div>
          <div v-else class="login-prompt-card">
             <el-avatar :size="50" :icon="UserFilled" />
            <h4>开启您的学习之旅</h4>
            <p>登录后查看更多精彩内容</p>
            <el-button type="success" round @click="goTo('/login')">登录 / 注册</el-button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- Partner schools -->
    <div class="partner-section">
      <div class="section-header">
        <h3 class="section-title">合作高校</h3>
      </div>
       <div class="partner-logos">
        <img v-for="logo in partnerLogos" :key="logo" :src="logo" alt="Partner Logo">
      </div>
    </div>

    <!-- Courses Section -->
    <div class="courses-section">
      <div class="section-header">
        <h2 class="section-title">精选课程</h2>
        <p class="section-subtitle">探索最受欢迎的课程</p>
      </div>
      
      <el-tabs v-model="activeTab" class="course-tabs">
        <el-tab-pane label="全部" name="all"></el-tab-pane>
        <el-tab-pane label="考研" name="postgraduate"></el-tab-pane>
        <el-tab-pane label="计算机" name="cs"></el-tab-pane>
        <el-tab-pane label="经济管理" name="management"></el-tab-pane>
      </el-tabs>

      <el-row :gutter="24" v-loading="loading">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="course in courses" :key="course.courseID" class="course-col">
          <el-card shadow="hover" :body-style="{ padding: '0px' }" class="course-card" @click="goToCourseDetail(course.courseID)">
            <div class="card-image-container">
              <img :src="course.img || 'https://via.placeholder.com/300x180'" class="course-image" />
              <div class="image-overlay">
                 <el-tag size="small" effect="dark" type="warning" class="course-tag">热门</el-tag>
              </div>
            </div>
            <div class="card-content">
              <h3 class="course-name">{{ course.name }}</h3>
              <p class="course-instructor">{{ course.instructor || '名师' }}</p>
              <div class="price-line">
                <span class="course-price" :class="{ 'free': course.price === 0 }">
                  {{ course.price === 0 ? '免费' : `¥ ${course.price.toFixed(2)}` }}
                </span>
                <span class="student-count">
                  <el-icon><User /></el-icon>
                  {{ course.studentCount || '100+' }}
                </span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <el-empty v-if="!loading && courses.length === 0" description="暂无课程"></el-empty>
      
      <div v-if="totalCourses > pageSize" class="pagination-container">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="totalCourses"
          :page-size="pageSize"
          v-model:current-page="currentPage"
          @current-change="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, shallowRef } from 'vue'
import { getCourseList } from '../api/course'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import banner1 from '../assets/b1.png'
import banner2 from '../assets/b2.png'
import banner3 from '../assets/b3.png'
import {
  Notebook,
  DataAnalysis,
  Trophy,
  Postcard,
  Cpu,
  Reading,
  Suitcase,
  UserFilled,
  User
} from '@element-plus/icons-vue'

// Partner logos (replace with your actual logo paths)
import pku from '../assets/pku.png';
import zju from '../assets/zju.png';
import nju from '../assets/nju.png';
import whu from '../assets/whu.png';
import fdu from '../assets/fdu.png';

const router = useRouter()
const userStore = useUserStore()

const carouselItems = ref([
  { id: 1, image: banner1 },
  { id: 2, image: banner2 },
  { id: 3, image: banner3 }
])

const categories = shallowRef([
  { name: '国家精品', sub: '学/工学/经济', icon: Trophy },
  { name: '考研', sub: '数学/英语/政治', icon: Notebook },
  { name: '认证学习', sub: '理学/工学/经济', icon: Postcard },
  { name: '期末突击', sub: '数学/物理/计...', icon: DataAnalysis },
  { name: '计算机', sub: '大数据/人工智能', icon: Cpu },
  { name: '理学工学农学', sub: '数学/物理/...', icon: Reading },
  { name: '求职就业', sub: 'Python / 财经金融', icon: Suitcase },
])

const partnerLogos = ref([pku, zju, nju, whu, fdu]);

const courses = ref([])
const totalCourses = ref(0)
const pageSize = ref(8)
const currentPage = ref(1)
const loading = ref(false)
const activeTab = ref('all')

const fetchCourses = async () => {
  loading.value = true
  try {
    const res = await getCourseList({
      page: currentPage.value,
      pageSize: pageSize.value
    })
    if (res.code === 1) {
      courses.value = (res.data.items || []).map(c => ({...c, studentCount: Math.floor(Math.random() * 5000) + 100 }));
      totalCourses.value = res.data.total
    } else {
      ElMessage.error(res.message || '获取课程失败')
      courses.value = []
      totalCourses.value = 0
    }
  } catch (error) {
    console.error('Failed to fetch courses:', error)
    ElMessage.error(error.message || '获取课程失败，请重试')
    courses.value = []
    totalCourses.value = 0
  } finally {
    loading.value = false
  }
}

const handlePageChange = (newPage) => {
  currentPage.value = newPage
  fetchCourses()
}

const goToCourseDetail = (courseId) => {
  router.push(`/course/${courseId}`)
}

const goTo = (path) => {
  router.push(path);
}

onMounted(() => {
  fetchCourses()
})
</script>

<style scoped>
.home-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 16px;
}

/* Top Section */
.top-section {
  background-color: #fff;
  padding: 20px 0;
  border-radius: 8px;
}

.main-content-wrapper {
  display: flex;
  gap: 20px;
}

/* Left Category Nav */
.left-category-nav {
  width: 220px;
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 8px 0;
}

.left-category-nav ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.left-category-nav li {
  display: flex;
  align-items: center;
  padding: 10px 16px;
  cursor: pointer;
  transition: background-color 0.3s;
  font-size: 14px;
}

.left-category-nav li:hover {
  background-color: #e9ecef;
}

.left-category-nav .el-icon {
  margin-right: 12px;
  font-size: 16px;
  color: #495057;
}

.left-category-nav .sub-text {
  margin-left: auto;
  font-size: 12px;
  color: #adb5bd;
}

/* Middle Content */
.middle-content {
  flex: 1;
  min-width: 0;
  border-radius: 8px;
  overflow: hidden;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* Right User Card */
.right-user-card {
  width: 240px;
  padding: 20px;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  text-align: center;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.user-info-card, .login-prompt-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.right-user-card .user-avatar {
  margin-bottom: 10px;
}

.right-user-card h4 {
  margin: 0;
  font-size: 16px;
}

.right-user-card p {
  margin: 0;
  font-size: 12px;
  color: #6c757d;
}

/* Partner Section */
.partner-section {
  padding: 30px 0;
  text-align: center;
}
.partner-logos {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 30px;
  flex-wrap: wrap;
  margin-top: 20px;
}

.partner-logos img {
  height: 40px;
  filter: grayscale(100%);
  opacity: 0.6;
  transition: all 0.3s;
}

.partner-logos img:hover {
  filter: grayscale(0%);
  opacity: 1;
}

/* Courses Section */
.courses-section {
  padding: 20px 0 40px;
}

.section-header {
  text-align: center;
  margin-bottom: 30px;
}

.section-title {
  font-size: 28px;
  font-weight: 600;
  margin: 0 0 10px;
}

.section-subtitle {
  font-size: 16px;
  color: #6c757d;
  margin: 0;
}

.course-tabs {
  margin-bottom: 20px;
}

:deep(.el-tabs__nav-wrap::after) {
  display: none;
}
:deep(.el-tabs__item) {
  font-size: 16px;
}

.course-col {
  margin-bottom: 24px;
}

.course-card {
  border-radius: 12px;
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;
}

.course-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0,0,0,0.1);
}

.card-image-container {
  position: relative;
  height: 180px;
}

.course-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
}

.image-overlay {
  position: absolute;
  top: 10px;
  left: 10px;
}

.card-content {
  padding: 16px;
}

.course-name {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.course-instructor {
  font-size: 12px;
  color: #909399;
  margin: 0 0 12px;
}

.price-line {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.course-price {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
}

.course-price.free {
  color: #67c23a;
}
.student-count {
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 4px;
}
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 